<?php

namespace App\Models\Api;
use App\Models\Api\Base;
use Cache;

/**
 * 骰子备注模型
 * Class DivinationNote
 * @package app\common\model
 */
class DivinationNote extends Base
{
    /**
     * 骰子备注的所有id
     */
    const REDIS_KEY_IDS = 'divination_note_ids_';
    /**
     * 骰子备注的详情
     */
    const REDIS_KEY_DETAIL = 'divination_note_detail_';

    protected $table = 'divination_note';
    protected $readonly = ['uid', 'did'];
    protected $insert = ['create_time', 'last_time'];
    protected $update = ['last_time'];

    // 自动设置时间
    protected function setCreateTimeAttr()
    {
        return time();
    }

    // 自动设置时间
    protected function setLastTimeAttr()
    {
        return time();
    }

    /**
     * 获取所有的数量
     * @param array $map
     * @return int
     */
    public function getCountAll($map = [])
    {
        //获取所有的ids
        return count($this->getList($map));
    }


    /**
     * 获取列表（注意备注没有分页）
     * @param array $map
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Collection|\think\Model
     */
    public function getListAll($map = [])
    {
        //获取所有的ids
        $divination_notes = $this->getList($map);
        if (count($divination_notes) == 0)
        {//如果ids为空，那么直接返回
            return $divination_notes;
        }

        $data_list = $this->getDetails($divination_notes);
        return $data_list;
    }


    /**
     * 获取所有的详情
     * @param array $all_list
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getDetails($all_list = [])
    {
        $result = [];
        $ids = $this->getAllNotCachedIds($all_list, self::REDIS_KEY_DETAIL);

        try
        {
            if (strlen($ids) > 0)
            {
                $result = $this->select('id','did','content','create_time')
                    ->whereIn('id',[$ids])
                    ->orderBy('id','DESC')
                    ->get();
                $result = json_decode(json_encode($result, true), true);

                if ($this->cache_on >= 1)
                    foreach ($result as $v)
                        Cache::set(self::REDIS_KEY_DETAIL . $v['id'], $v, $this->cache_time);
            }
            if ($this->cache_on >= 1)//如果缓存打开，循环获取，因为缓存里已经有了数据
            {
                $result = [];
                foreach ($all_list as $v)
                    $result[] = Cache::get(self::REDIS_KEY_DETAIL . $v['id']);
            }
        }
        catch (\Exception $e)
        {
            // 错误信息写入日志
            \Log::info('获取骰子备注错误:' . '[' . $ids . ']');
        }


        return $result;
    }

    /**
     * 获取所有的ids
     * @param array $map
     * @return bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    private function getList($map = [])
    {
        //获取 用户所有占卜的id
        $divination_notes = false;
        if ($this->cache_on >= 1 && Cache::has(self::REDIS_KEY_IDS . $map['did']))
        {
            $divination_notes = Cache::get(self::REDIS_KEY_IDS . $map['did']);
        }
        if ($divination_notes === false)
        {
            try
            {
                $divination_notes = $this
                    ->select('id')
                    ->where(['did' => $map['did'], 'uid' => $map['uid']])
                    ->orderBy('create_time', 'DESC')
                    ->get();
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \Log::info('获取骰子备注错误:' . '[' . $map['did'] . ']');
            }
            //获取数据
            $divination_notes = json_decode(json_encode($divination_notes, true), true);

            //存储所有ids
            $cache_data = '';
            foreach ($divination_notes as $k => $v)
            {
                $cache_data .= ',' . $v['id'];
            }
            if ($this->cache_on >= 1)
            {
                Cache::set(self::REDIS_KEY_IDS . $map['did'], $divination_notes, $this->cache_time);
            }
        }

        return $divination_notes;
    }
}
